package com.threeman.maper.map;

import java.util.ArrayList;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Point;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.Log;

import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapView;
import com.threeman.maper.MainActivity;

public class DirectionOverly extends ItemizedOverlay<DirectionItem>
{

	private static String TAG = "DirectionOverlay";

	private Context mContext;

	private Drawable mDefaultMarker;

	private ArrayList<DirectionItem> mOverlays = new ArrayList<DirectionItem>();

	private Bitmap mBitmap;

	private Bitmap mBitmapToDraw;

	private float mScale = 1.0f;


	public float getScale()
	{
		return mScale;
	}


	public void setScale(float mScale)
	{
		if (mScale > 0.0f && mScale < 1.0f)
		{
			this.mScale = mScale;

			Matrix matrix = new Matrix();
			matrix.postScale(mScale, mScale);

			mBitmapToDraw = Bitmap.createBitmap(mBitmap, 0, 0, mBitmap.getWidth(), mBitmap.getHeight(), matrix, true);
		}
	}


	public void setDefaultMarker(Drawable defaultMarker)
	{
		this.mDefaultMarker = defaultMarker;

		mBitmap = ((BitmapDrawable) defaultMarker).getBitmap();
		mBitmapToDraw = mBitmap;
	}


	public DirectionOverly(Drawable defaultMarker, Context context)
	{
		super(defaultMarker);
		mContext = context;
		setDefaultMarker(defaultMarker);
	}


	@Override
	protected DirectionItem createItem(int i)
	{
		return mOverlays.get(i);
	}


	@Override
	public int size()
	{
		return mOverlays.size();
	}


	public void addOverlay(DirectionItem overlay)
	{
		if (this.size() == 0)
		{
			mOverlays.add(overlay);
			populate();
		}
	}


	@Override
	public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when)
	{
		try
		{
			if (this.size() == 0)
				return false;
			else if (this.size() == 1)
			{
				canvas.save();

				Point screenPoint = new Point();
				mapView.getProjection().toPixels(mOverlays.get(0).getPoint(), screenPoint);

				int x = screenPoint.x - mBitmapToDraw.getWidth() / 2;
				int y = screenPoint.y - mBitmapToDraw.getHeight() / 2;

				int px = screenPoint.x;// + mBitmap.getWidth() / 2;
				int py = screenPoint.y;

				Matrix mat = canvas.getMatrix();

				// mat.preRotate(-mRotation, px, py);
				mat.preRotate(mOverlays.get(0).getRotation(), px, py);

				canvas.setMatrix(mat);

				super.draw(canvas, mapView, shadow, when);

				canvas.drawBitmap(mBitmapToDraw, x, y, null);

				canvas.restore();

				return true;
			} else
				return false;
		} catch (Exception ex)
		{
			Log.w(MainActivity.APPTAG, TAG + " : error ", ex);
			return false;
		}

	}

}
